package com.ccdt.tv.smartrecommend.service;


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.ccdt.tv.smartrecommend.Constant;
import com.ccdt.tv.smartrecommend.FromLiveBean;
import com.ccdt.tv.smartrecommend.ISmartRecommendService;
import com.ccdt.tv.smartrecommend.presenter.SmartService.SmartServiceContract;
import com.ccdt.tv.smartrecommend.presenter.SmartService.SmartServicePresenter;
import com.ccdt.tv.smartrecommend.utils.GetTokenServiceHelper;
import com.google.gson.Gson;

/**
 * 跟其他应用交互的service
 */
public class SmartService extends Service implements GetTokenServiceHelper.OnCaCardChanged, SmartServiceContract.View {

	private static String TAG = "SmartService";
	public static final String KEY_LIVE_TO_RECOMMEND = "KEY_LIVE_TO_RECOMMEND"; //直播连接key
	private SmartServicePresenter mPresenter;
	private static long mTime;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.e(TAG, "onCreate");
		mPresenter = new SmartServicePresenter();
		mPresenter.attachView(this);
	}

	Binder mBinder = new ISmartRecommendService.Stub(){
		@Override
		public void sendLiveData(String key,FromLiveBean bean) throws RemoteException {
			Log.w(TAG, "SendLiveData: FromLiveBean："+bean.toString() );
			if(!TextUtils.isEmpty(key)&&key.equals(KEY_LIVE_TO_RECOMMEND)){
				//如果key匹配则执行保存操作
				SPUtils.getInstance(Constant.SP_NAME).put(Constant.SP_LIVE_JSON,new Gson().toJson(bean));
//				mPresenter.createHitChannels();
			}
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.w(TAG, "onStartCommand: " );
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mPresenter.detachView();
//		mPresenter.finishHitChannels();
	}

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
//		Log.w(TAG, "onBind: "+(System.currentTimeMillis()-mTime));
//		if (System.currentTimeMillis()-mTime>20000){
//			mPresenter.createLiveRecommend();
//			mTime = System.currentTimeMillis();
//		}
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.w(TAG, "onUnbind: " );
//		mPresenter.finishLiveRecommend();
		return true;
	}

	@Override
	public void onCaCardChanged() {
		//CA卡更换
	}
}
